package org.millioncall.yueyoga.common.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.millioncall.openplatform.util.WebAppUtils;
import org.millioncall.yueyoga.admin.model.User;
import org.millioncall.yueyoga.common.GlobalConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;

/**
 * 
 * @author zangjinyu
 * @since 2014-3-9
 * @version 1.0.0
 * 
 */
public class ZhuwLoginAuthenticationSuccessHandler extends
		SimpleUrlAuthenticationSuccessHandler {
	protected final Logger logger = LoggerFactory
			.getLogger(ZhuwLoginAuthenticationSuccessHandler.class);
	private RequestCache requestCache = new HttpSessionRequestCache();
	private boolean enableAjaxLoginSuccessHandler = false;// 是否启用ajax登录处理器

	/**
	 * 处理ajax请求
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void handlerAjaxLoginSuccessResponse(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		clearAuthenticationAttributes(request);
		User user = (User) request.getSession().getAttribute(
				GlobalConstants.LOGIN_USER_KEY);
		String msg = "{'success':true,'type':'successfullyAuthenticated','msg':'认证成功','username':'"
				+ user.getUsername() + "'}";
		WebAppUtils.ajaxResponse(response, msg);
	}

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws ServletException, IOException {

		// 从缓存中获取缓存的request。spring
		// security默认是会在ExceptionTranslationFilter过滤器的sendStartAuthentication方法中保存request的。
		SavedRequest savedRequest = requestCache.getRequest(request, response);

		// 如果没有缓存请求之前的request
		if (savedRequest == null) {
			if (this.enableAjaxLoginSuccessHandler
					&& WebAppUtils.isAjaxRequest(request)) {
				handlerAjaxLoginSuccessResponse(request, response);
			} else {
				super.onAuthenticationSuccess(request, response, authentication);
			}
			return;
		}

		String targetUrlParameter = getTargetUrlParameter();
		// 如果始终使用默认的目标转向url
		if (isAlwaysUseDefaultTargetUrl()
				|| (targetUrlParameter != null && StringUtils.hasText(request
						.getParameter(targetUrlParameter)))) {
			requestCache.removeRequest(request, response);
			if (this.enableAjaxLoginSuccessHandler
					&& WebAppUtils.isAjaxRequest(request)) {
				handlerAjaxLoginSuccessResponse(request, response);
			} else {
				super.onAuthenticationSuccess(request, response, authentication);
			}
			return;
		}

		// 从缓存的request中取得要跳转的url
		clearAuthenticationAttributes(request);
		String targetUrl = savedRequest.getRedirectUrl();
		logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
		getRedirectStrategy().sendRedirect(request, response, targetUrl);
	}

	public void setRequestCache(RequestCache requestCache) {
		this.requestCache = requestCache;
	}

	public void setEnableAjaxLoginSuccessHandler(
			boolean enableAjaxLoginSuccessHandler) {
		this.enableAjaxLoginSuccessHandler = enableAjaxLoginSuccessHandler;
	}
}
